﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Singer.Middleware.Redis;
using StackExchange.Redis;

namespace Singer.UnitTestWeb.Controllers
{
    [AllowAnonymous]
    public class RedisController : ApiControllerBase
    {
        IRedisConnectionPool _redisConnectionPool;
        public RedisController(IServiceProvider serviceProvider, IRedisConnectionPool redisConnectionPool) : base(serviceProvider)
        {
            _redisConnectionPool = redisConnectionPool;
        }

        [HttpGet]
        public async Task RedisTest(string key, string hashKey, string value)
        {
            var db = _redisConnectionPool.GetDatabase(3);
            await db.HashSetAsync(key, hashKey, value);
            var _value = await db.HashGetAsync(key, hashKey);
            //var devdb = _redisConnectionPool.GetDatabase(3, "DevRedis");
            //await devdb.HashSetAsync(key, hashKey, value);
            //return await devdb.HashGetAsync(key, hashKey);
        }

        [HttpGet]
        public async Task RedisTest2()
        {
            //测试RedisKey不存在时，调用方法会不会报错
            var db = _redisConnectionPool.GetDatabase(3);
            //bool a = await db.KeyDeleteAsync("km_set");//不会报错，返回false
            await db.SetRemoveAsync("km_set", "1");//不会报错 不会创建key，
            await db.HashDeleteAsync("km_hash", "1");//不会报错 不会创建key，
            bool result = await db.SetContainsAsync("km_set", "1");//不会报错 不会创建key，结果false
            long length = await db.SetLengthAsync("km_set");//不会报错 不会创建key，结果0
        }

        [HttpGet]
        public async Task RedisScanKeys()
        {
            //遍历匹配规则的key的全部值。使用Scan游标遍历 相当于分页遍历
            string pattern = $"aaa:bb:*";
            int batchSize = 10;//一次性查找的个数。 （是一次查找的总数。而不是匹配结果的数量） 
            long cursor = 0;//遍历之后，下次遍历开始的游标 （应该是查找的最后一个key的游标）
            //如果key数量等于batchSize，cursor有值，下次还会遍历。
            //key小于batchSize，cursor为0。下次不会遍历。

            List<string> values = new List<string>();
            var db = _redisConnectionPool.GetDatabase(3);
            int foreachCount = 0;
            do
            {
                foreachCount++;
                var scanResult = await db.ExecuteAsync("SCAN", cursor.ToString(), "MATCH", pattern, "COUNT", batchSize.ToString());
                RedisResult[] results = (RedisResult[])scanResult;
                cursor = long.Parse((string)results[0]);
                RedisKey[] keys = (RedisKey[])results[1];
                foreach (var key in keys)
                {
                    await foreach (var item in db.SetScanAsync(key))
                    {
                        values.Add(item.ToString());
                    }
                }
            } while (cursor != 0);

        }
    }
}
